package gofish.servlets;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import gofish.dao.DAOException;
import gofish.dao.GoFishDAOHandler;
import gofish.json.JsonObject;

/**
 * JoinGroup will be a Servlet that Adam's client code can contact to join a
 * group from the lobby screen.
 * 
 * @author Matt Lauber
 */
public class JoinGroup extends HttpServlet {

	/**
	 * At this point, I don't believe what sort of JSON it returns has been
	 * determined.
	 */
	// public boolean doPost(int gid, String userName) {
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setContentType("application/json");

		PrintWriter out = response.getWriter();
		try {
		JsonObject jsonResponse = new JsonObject();
			String userName = request.getParameter("userName");
			int gid = Integer.parseInt(request.getParameter("gid"));

			GoFishDAOHandler handler = new GoFishDAOHandler(getServletContext());
			handler.joinGroup(gid, userName);
			jsonResponse = new JsonObject("success", true);
			// System.out.println(response);

		// return game;
		out.print(jsonResponse.toString());
		} catch (Exception e) {
			JsonObject json = new JsonObject();
			StringBuilder builder = new StringBuilder();
			for (StackTraceElement elem : e.getStackTrace()) {
				builder.append(elem.toString() + " ");
			}
			json.add("error", builder.toString());
			out.print(json.toString());
		}
		out.flush();
	}
}
